package com.tarry.exception;

import com.tarry.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AppExceptionReslover implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse reqs, Object o, Exception e) {
        String url = req.getRequestURL().toString();
        ModelAndView mv ;
        String defaultMsg = "系统异常，请联系系统管理员进行处理···";
        Result result;
        if( url.endsWith(".json")){//控制json请求只能以.json结尾
            if( e instanceof AppException || e instanceof ParamException){
                result = Result.error(e.getMessage());
            }else {
                log.error("unknow json exception,url:" +url , e);
                result = Result.error(defaultMsg);
            }
            mv = new ModelAndView("jsonView",Result.toMap(result));
        }else if( url.endsWith(".do")){//控制页面请求只能是.do结尾
            log.error("unknow view exception,url:" +url , e);
            result = Result.error(defaultMsg);
            mv = new ModelAndView("exception",Result.toMap(result));
        }else {
            log.error("unknow exception,url:" +url , e);
            result = Result.error(defaultMsg);
            mv = new ModelAndView("jsonView",Result.toMap(result));
        }
        return mv;
    }
}
